package com.gitee.feizns.web.boot.data;

import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.spring.boot.starter.MybatisPlusProperties;
import com.gitee.feizns.web.dao.handler.meta.CreatedAtAutoFillHandler;
import com.gitee.feizns.web.dao.handler.meta.EncodingAutoHandler;
import com.gitee.feizns.web.dao.handler.meta.FillGeneratorHandler;
import com.gitee.feizns.web.dao.handler.meta.FillInputHandler;
import com.gitee.feizns.web.dao.handler.meta.GeneralMetaObjectHandler;
import com.gitee.feizns.web.dao.handler.meta.RedundancyAutoFillHandler;
import com.gitee.feizns.web.dao.handler.type.JSONArrayTypeHandler;
import com.gitee.feizns.web.dao.handler.type.JSONObjectTypeHandler;
import com.gitee.feizns.web.dao.handler.type.ListTypeHandler;
import com.gitee.feizns.web.dao.handler.type.SetTypeHandler;
import com.gitee.feizns.web.dao.intercepter.TotalPaginationInterceptor;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author feizns
 * @since 2019/7/25
 */
@Configuration
public class MybatisPlusAutoConfiguration implements ApplicationContextAware {

    @Bean
    public TotalPaginationInterceptor paginationInterceptor() {
        return new TotalPaginationInterceptor();
    }

    @Bean
    public GeneralMetaObjectHandler generalMetaObjectHandler(List<FillInputHandler> handlers) {
        return new GeneralMetaObjectHandler(handlers);
    }

    @Bean
    public CreatedAtAutoFillHandler createdAtAutoFillHandler() {
        return new CreatedAtAutoFillHandler();
    }

    @Bean
    public RedundancyAutoFillHandler redundancyAutoFillHandler() {
        return new RedundancyAutoFillHandler();
    }

    @Bean
    public FillGeneratorHandler fillGeneratorHandler() {
        return new FillGeneratorHandler();
    }

    @Bean
    public EncodingAutoHandler encodingAutoHandler() {
        return new EncodingAutoHandler();
    }

    @Override
    public void setApplicationContext(ApplicationContext app) throws BeansException {
        MybatisPlusProperties bean = app.getBean(MybatisPlusProperties.class);
        if ( bean != null ) {
            MybatisConfiguration configuration = bean.getConfiguration();
            if ( configuration != null ) {
                configuration.getTypeHandlerRegistry().register(ListTypeHandler.class);
                configuration.getTypeHandlerRegistry().register(SetTypeHandler.class);
                configuration.getTypeHandlerRegistry().register(JSONArrayTypeHandler.class);
                configuration.getTypeHandlerRegistry().register(JSONObjectTypeHandler.class);
            }
        }
    }

}
